import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;
    private Object NullPointerException;

    public PriorityQueue() {
        elem = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        if(elem.length < array.length){
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        for (int i = 0; i < array.length; i++){
            elem[i] = array[i];
            usedSize++;
        }
        for (int root = (usedSize -1 -1) / 2; root >= 0 ; root--) {
            shiftDown(root,usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root * 2 + 1;
        while (child < len){
            //寻找孩子节点的大值
            if(child + 1 < len && elem[child] < elem[child + 1]){
                child++;
            }
            if(elem[root] < elem[child]){
                swap(elem,root,child);
                root = child;
                child = root * 2 + 1;
            }else {
                break;
            }
        }
    }
    //交换函数
    private void swap(int[] array,int x,int y){
        int tmp = array[x];
        array[x] = array[y];
        array[y] = tmp;
    }

    /**
     * 入堆：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem = Arrays.copyOf(elem, elem.length*2);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(parent >= 0) {
            if (elem[parent] < elem[child]) {
                swap(elem, parent, child);
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() throws  NullPointerException{
        if(isEmpty()){
            throw new NullPointerException();
        }
        swap(elem,0,usedSize-1);
        shiftDown(0,usedSize);
        usedSize--;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() throws NullPointerException {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        return elem[0];

    }
}
